﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Prototype.FetchBall
{
    public class SpawnManagerX : MonoBehaviour
    {
        public GameObject[] ballPrefabs;

        private float spawnLimitXLeft = -22;
        private float spawnLimitXRight = 7;
        private float spawnPosY = 30;

        private float startDelay = 1.0f;
        private float spawnIntervalMin = 1.5f;
        private float spawnIntervalMax = 3.5f;

        // Start is called before the first frame update
        void Start()
        {
            StartCoroutine(RepeatSpawnBall());
        }
        
        IEnumerator RepeatSpawnBall()
        {
            yield return new WaitForSeconds(startDelay);
            float nextSpawnTime = 0;
            float nextSpawnInterval = Random.Range(spawnIntervalMin,spawnIntervalMax);
            while (true)
            {
                nextSpawnTime += Time.deltaTime;
                if(nextSpawnTime > nextSpawnInterval)
                {
                    nextSpawnTime = 0;
                    nextSpawnInterval = Random.Range(spawnIntervalMin,spawnIntervalMax);
                    SpawnRandomBall();
                }
                yield return null;
            }
        }

        // Spawn random ball at random x position at top of play area
        void SpawnRandomBall()
        {
            // Generate random ball index and random spawn position
            Vector3 spawnPos = new Vector3(Random.Range(spawnLimitXLeft, spawnLimitXRight), spawnPosY, 0);
            int randomBallIndex = Random.Range(0,ballPrefabs.Length);
            // instantiate ball at random spawn location
            Instantiate(ballPrefabs[randomBallIndex], spawnPos, ballPrefabs[randomBallIndex].transform.rotation);
        }
    }
}